<template>
  <div class="pd15">
    <a-modal v-model="showAddFilterDialog" title="新增过滤器" @ok="saveFilter">
      <ZgInput v-model="filterName" placeholder="请输入过滤器名称"></ZgInput>
    </a-modal>
    <a-form v-if="obj!==null" :labelCol="{ span: labelCol }" :wrapperCol="{ span: 24-labelCol }">
      <a-row>
        <a-col v-for="(c,i) in conditions" :key="`condition${i}`" :span="columnCol">
          <a-form-item :label="c.label" style="margin-bottom:0;">
            <ZgDateRangePicker v-if="c.compType==='日期区间'" @change="v=>onRangeChange(v,c.code)"></ZgDateRangePicker>
            <div v-if="c.compType==='整数区间'" class="flx-s">
              <ZgNumber style="width:45%" v-model="obj[c.code+'_s']"></ZgNumber>
              <div>&nbsp;至&nbsp;</div>
              <ZgNumber style="width:45%" v-model="obj[c.code+'_e']"></ZgNumber>
            </div>
            <ZgDatePicker v-if="c.compType==='日期'" v-model="obj[c.code]"></ZgDatePicker>
            <ZgNumber v-if="c.compType==='整数'" v-model="obj[c.code]"></ZgNumber>
            <ZgInput v-if="c.compType==='单行文本'" v-model="obj[c.code]"></ZgInput>
            <ZgDictionary v-if="c.compType==='字典'" :code="c.extra.字典类型" v-model="obj[c.code]"></ZgDictionary>
            <ZgSelect v-if="c.compType==='下拉选择'" :options="c.extra.下拉选项" v-model="obj[c.code]"></ZgSelect>
            <ZgSelect v-if="c.compType==='布尔'" :options="[{value:'true',label:'是'},{value:'false',label:'否'}]" v-model="obj[c.code]"></ZgSelect>
          </a-form-item>
        </a-col>
        <a-col :span="6" v-if="showInlineBtn">
          <div class="flx-s pt4 ml15">
            <ZgButton @click="reset" type="default" class="mr10" icon="refresh">重置</ZgButton>
            <ZgButton @click="searchWithCondition" icon="search">查询</ZgButton>
          </div>
        </a-col>
      </a-row>
    </a-form>
    <div class="flx-e mt10">
      <ZgDropdown
        v-if="showFilterAdminBtn"
        @click="onClickFilterBtn"
        type="link"
        class="mr10"
        :opts="[{key:1,label:'存为新的过滤器'},{key:2,label:'更新过滤器'},{key:3,label:'删除过滤器'}]">
        管理过滤器<i class="fa fa-ellipsis-h ml5"/>
      </ZgDropdown>
      <ZgButton v-if="!showInlineBtn" @click="reset" type="default" class="mr10" icon="refresh">重置</ZgButton>
      <ZgButton v-if="!showInlineBtn" @click="searchWithCondition" icon="search">查询</ZgButton>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    uniqueName: {
      type: String,
      default: 'test'
    },
    labelCol: {
      type: Number,
      default: 6
    },
    columnCol: {
      type: Number,
      default: 6
    },
    currFilterName: {
      type: String,
      default: ''
    },
    showFilterAdminBtn: {
      type: Boolean,
      default: false
    },
    showInlineBtn: {
      type: Boolean,
      default: true
    },
    conditions: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      obj: null,
      defaultObj: null, // 保存初始化默认值
      showAddFilterDialog: false,
      filterName: ''
    }
  },
  mounted () {
    this.initData()
    this.calculateHeight()
  },
  methods: {
    calculateHeight () {
      this.$emit('height', (this.showInlineBtn ? 30 : 70) + Math.ceil((this.conditions.length + (this.showInlineBtn ? 1 : 0)) / (24 / this.columnCol)) * 40)
    },
    getCondition () {
      return JSON.stringify(this.obj)
    },
    set (t) {
      this.obj = Object.assign({}, this.defaultObj, JSON.parse(t))
    },
    reset () {
      // 所有参数设置默认值
      this.obj = Object.assign({}, this.defaultObj)
    },
    searchWithCondition () {
      // 查询参数
      this.$emit('search', this.getCondition())
    },
    saveFilter () {
      // 保存过滤器
      if (!this.filterName || this.filterName.length === 0) {
        this.$error({ title: '请输入过滤器名称！' })
        return
      }
      const condition = this.getCondition()
      const key = this.currentUser.username + '_diyFilter_' + this.uniqueName
      const diyFilters = localStorage.getItem(key)
      if (!diyFilters) {
        localStorage.setItem(key, JSON.stringify([{
        name: this.filterName,
        count: 0,
        condition: condition
      }]))
      } else {
        const arr = JSON.parse(diyFilters)
        if (arr.some(t => {
          return t.name === this.filterName
        })) {
          this.$error({ title: '过滤器名称已经被使用！' })
          return
        }
        arr.unshift({
          name: this.filterName,
          count: 0,
          condition: condition
        })
        localStorage.setItem(key, JSON.stringify(arr))
      }
      this.showAddFilterDialog = false
      this.$success({ title: '操作成功！' })
      this.$emit('refresh', true)
    },
    onRangeChange (v, code) {
      this.obj[code + '_s'] = v[0]
      this.obj[code + '_e'] = v[1]
    },
    initData () {
      const json = {}
      this.conditions.forEach(c => {
        if (c.compType === '日期区间') {
          json[c.code + '_s'] = c.defaultVal[0]
          json[c.code + '_e'] = c.defaultVal[1]
          json[c.code] = []
        } else if (c.compType === '整数区间') {
          json[c.code + '_s'] = c.defaultVal[0]
          json[c.code + '_e'] = c.defaultVal[1]
        } else {
          json[c.code] = c.defaultVal
        }
      })
      this.obj = json
      this.defaultObj = JSON.parse(JSON.stringify(json))
    },
    onClickFilterBtn (t) {
      if (t.key === 1) {
        this.filterName = ''
        this.showAddFilterDialog = true
      } else if (t.key === 2) {
        // 更新过滤器
        const key = this.currentUser.username + '_diyFilter_' + this.uniqueName
        const diyFilters = localStorage.getItem(key)
        if (!diyFilters) {
          this.$error({ title: '没有过滤器！' })
          return
        }
        if (diyFilters) {
          const arr = JSON.parse(diyFilters)
          if (!arr.some(t => {
            return t.name === this.currFilterName
          })) {
            this.$error({ title: '没有此过滤器！' })
            return
          }
          const newArr = arr.map(t => {
             if (t.name === this.currFilterName) {
              t.condition = this.getCondition()
            }
            return t
          })
          localStorage.setItem(key, JSON.stringify(newArr))
          this.$success({ title: '操作成功' })
          this.$emit('refresh', false)
        }
      } else if (t.key === 3) {
        // 删除过滤器
        const key = this.currentUser.username + '_diyFilter_' + this.uniqueName
        const diyFilters = localStorage.getItem(key)
        if (!diyFilters) {
          this.$error({ title: '没有过滤器！' })
          return
        }
        if (diyFilters) {
          const arr = JSON.parse(diyFilters)
          if (!arr.some(t => {
            return t.name === this.currFilterName
          })) {
            this.$error({ title: '没有此过滤器！' })
            return
          }
          const newArr = arr.filter(t => {
            return t.name !== this.currFilterName
          })
          if (newArr.length === 0) {
            localStorage.removeItem(key)
          } else {
            localStorage.setItem(key, JSON.stringify(newArr))
          }
          this.$success({ title: '操作成功' })
          this.$emit('refresh', true)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
